package com.cloud.user.web;

import com.cloud.platform.BaseHandler;
import com.cloud.platform.util.Constants;
import com.cloud.user.model.User;
import com.cloud.user.service.UserService;

public class UserBean extends BaseHandler {

	private UserService userService;
	
	private String originPassword;
	private String sign;
	
	/**
	 * save user's sign 
	 */
	public void saveSign() {
		
		try {
			userService.saveUserSign(getLoginUserId(), sign);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * get user's personal sign
	 * 
	 * @return
	 */
	public String getSign() {
		
		if(sign == null) {
			try {
				sign = userService.getUserSign(getLoginUserId());
				
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		return sign;
	}

	/**
	 * get user's origin password
	 * 
	 * @return
	 */
	public String getOriginPassword() {
		
		if(originPassword == null) {
			try {
				originPassword = userService.getUserPassword(getLoginUserId());
				
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		return originPassword;
	}

	/**
	 * user login
	 * 
	 * @return
	 */
	public String login() {
		
		User loginUser = userService.checkLogin(getParameter("username"),
				getParameter("password"));
		
		if(loginUser != null) {
			getSession().setAttribute(Constants.LOGIN_USER, loginUser.getId());
			getSession().setAttribute(Constants.LOGIN_USERNAME, loginUser.getUsername());
			
			return "success";
		}
		
		return "";
	}
	
	/**
	 * user register
	 * 
	 * @return
	 */
	public String register() {
		
		userService.register(getParameter("username"),
				getParameter("password"), getParameter("email"));
		
		return "success";
	}
	
	/**
	 * change user password
	 */
	public void changePassword() {
		
		try {
			userService.changePassword(getLoginUserId(), getParameter("password"));
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * =======================  getters and setters  =======================
	 */
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void setOriginPassword(String originPassword) {
		this.originPassword = originPassword;
	}
	
	public void setSign(String sign) {
		this.sign = sign;
	}
}
